package com.btpn.infra.utils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import java.util.Vector;

import org.apache.commons.io.FileUtils;

import com.btpn.custody.common.Constant;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.ChannelSftp.LsEntry;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;
import com.jcraft.jsch.UserInfo;

public class MySFTPclient {

//	private final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(this.getClass());
	
	private static String USER;
	private static String HOST;
	private static int PORT;
	private static String DEST_PATH;	// for real change to 'in'
	private static String SRC_PATH;
	private static String FILE_PATH;
	
	public static String putEQ(InputStream isSrc, String filename) {
        
		byte[] emptyPassPhrase = null;  // Empty passphrase for now, get real passphrase from MyUserInfo
		byte[] prvkey;
		try {				
			MySFTPclient a = new MySFTPclient();
			Properties prop = new Properties();
			prop.load(a.getClass().getClassLoader().getResourceAsStream("sftp.properties"));

			USER = prop.getProperty("user");
			HOST = prop.getProperty("host");
			PORT = Integer.parseInt(prop.getProperty("port"));
			DEST_PATH = prop.getProperty("dest_path");
			SRC_PATH = prop.getProperty("src_path");
			FILE_PATH = prop.getProperty("file_path");
			
			prvkey = FileUtils.readFileToByteArray(new File(FILE_PATH));			
		} catch (IOException e) {
			System.out.println("ERROR GET PRIVATE KEY (when putEQ) : " + e);
			return Constant.STATUS__FAIL + " : " + e.getMessage();
		}        

		JSch jSch = new JSch();    
		Session session=null;
		Channel channel=null;
		ChannelSftp sftp=null;
        try {
			jSch.addIdentity(
			    USER, 		        // String userName
			    prvkey,             // byte[] privateKey 
			    null,               // byte[] publicKey
			    emptyPassPhrase     // byte[] passPhrase
			);
		    
	        UserInfo ui = new MyUserInfo();
	        session = jSch.getSession(USER, HOST, PORT);
	        session.setUserInfo(ui);
	        session.connect();
	        
	        channel = session.openChannel("sftp");
	        sftp = (ChannelSftp) channel;
	        sftp.connect();
			sftp.put(isSrc, DEST_PATH + filename);
//	        sftp.put(isSrc, DEST_PATH + "asd");
//	        sftp.rename(DEST_PATH + "asd", DEST_PATH + "after");
	        
	        return Constant.STATUS__SUCCESS;
        } catch (JSchException e) {
        	System.out.println("ERROR PUT : " + e);
			return Constant.STATUS__FAIL + " : " + e.getMessage();
		} catch (SftpException e) {
			System.out.println("ERROR PUT : " + e);
			return Constant.STATUS__FAIL + " : " + e.getMessage();
		} finally {
			if (sftp!=null) sftp.disconnect();
			if (channel!=null) channel.disconnect();
	        if (session!=null) session.disconnect();
		}
    }
	
	// get all list of filenames
	public static List<String> getFilenames() {
		List<String> results = new ArrayList<String>();
		
		byte[] emptyPassPhrase = null;  // Empty passphrase for now, get real passphrase from MyUserInfo
		byte[] prvkey;
		try {
			MySFTPclient a = new MySFTPclient();
			Properties prop = new Properties();
			prop.load(a.getClass().getClassLoader().getResourceAsStream("sftp.properties"));

			USER = prop.getProperty("user");
			HOST = prop.getProperty("host");
			PORT = Integer.parseInt(prop.getProperty("port"));
			DEST_PATH = prop.getProperty("dest_path");
			SRC_PATH = prop.getProperty("src_path");
			FILE_PATH = prop.getProperty("file_path");
			
			prvkey = FileUtils.readFileToByteArray(new File(FILE_PATH));			
		} catch (IOException e) {
			System.out.println("ERROR GET PRIVATE KEY (when getFilenames) : " + e);
			return null;
		}        

		JSch jSch = new JSch();   
		Session session=null;
		Channel channel=null;
		ChannelSftp sftp=null;
        try {
			jSch.addIdentity(
			    USER, 		        // String userName
			    prvkey,             // byte[] privateKey 
			    null,               // byte[] publicKey
			    emptyPassPhrase     // byte[] passPhrase
			);
		        
	        UserInfo ui = new MyUserInfo();
	        session = jSch.getSession(USER, HOST, PORT);
	        session.setUserInfo(ui);
	        session.connect();
	        
	        channel = session.openChannel("sftp");
	        sftp = (ChannelSftp) channel;
	        sftp.connect();
	        
	        @SuppressWarnings("unchecked")
			Vector<LsEntry> v = sftp.ls(SRC_PATH);
	        for (int i=0; i<v.size(); i++) {
	        	
	        	String filename = ((LsEntry)v.get(i)).getFilename();
	        	if ((filename.contains("CMC")) | (filename.contains("CMD"))) {
	        		results.add(filename);
	        	}
	        }
	        
	        return results;
        } catch (JSchException e) {
        	System.out.println("ERROR GET FILENAMES : " + e);
			return null;
		} catch (SftpException e) {
			System.out.println("ERROR GET FILENAMES : " + e);
			return null;
		} finally {
			if (sftp!=null) sftp.disconnect();
			if (channel!=null) channel.disconnect();
	        if (session!=null) session.disconnect();
		}	
	}
	
	public static void removeFilenames(List<String> filenames) {
		
		byte[] emptyPassPhrase = null;  // Empty passphrase for now, get real passphrase from MyUserInfo
		byte[] prvkey = null;
		try {
			MySFTPclient a = new MySFTPclient();
			Properties prop = new Properties();
			prop.load(a.getClass().getClassLoader().getResourceAsStream("sftp.properties"));

			USER = prop.getProperty("user");
			HOST = prop.getProperty("host");
			PORT = Integer.parseInt(prop.getProperty("port"));
			DEST_PATH = prop.getProperty("dest_path");
			SRC_PATH = prop.getProperty("src_path");
			FILE_PATH = prop.getProperty("file_path");
			
			prvkey = FileUtils.readFileToByteArray(new File(FILE_PATH));
		} catch (IOException e) {
			System.out.println("ERROR GET PRIVATE KEY (when removeFilenames) : " + e);
		}

		JSch jSch = new JSch(); 
		Session session=null;
		Channel channel=null;
		ChannelSftp sftp=null;
        try {
			jSch.addIdentity(
			    USER, 		        // String userName
			    prvkey,             // byte[] privateKey 
			    null,               // byte[] publicKey
			    emptyPassPhrase     // byte[] passPhrase
			);
		        
	        UserInfo ui = new MyUserInfo();
	        session = jSch.getSession(USER, HOST, PORT);
	        session.setUserInfo(ui);
	        session.connect();
	        
	        channel = session.openChannel("sftp");
	        sftp = (ChannelSftp) channel;
	        sftp.connect();
	        
	        for (String filename : filenames) {
	        	sftp.rm(SRC_PATH + filename);
	        	System.out.println("REMOVE File : " + SRC_PATH + filename);
	        }
	        
        } catch (JSchException e) {
        	System.out.println("ERROR REMOVE FILENAMES : " + e);
		} catch (SftpException e) {
			System.out.println("ERROR REMOVE FILENAMES : " + e);
		} finally {
			if (sftp!=null) sftp.disconnect();
			if (channel!=null) channel.disconnect();
	        if (session!=null) session.disconnect();
		}	
	}
	
	public static InputStream getResponseEQ(String filename) {
        
		InputStream results;
		
		byte[] emptyPassPhrase = null;  // Empty passphrase for now, get real passphrase from MyUserInfo
		byte[] prvkey;
		try {
			MySFTPclient a = new MySFTPclient();
			Properties prop = new Properties();
			prop.load(a.getClass().getClassLoader().getResourceAsStream("sftp.properties"));

			USER = prop.getProperty("user");
			HOST = prop.getProperty("host");
			PORT = Integer.parseInt(prop.getProperty("port"));
			DEST_PATH = prop.getProperty("dest_path");
			SRC_PATH = prop.getProperty("src_path");
			FILE_PATH = prop.getProperty("file_path");
			
			prvkey = FileUtils.readFileToByteArray(new File(FILE_PATH));
		} catch (IOException e) {
			System.out.println("ERROR GET PRIVATE KEY (when getResponseEQ) : " + e);
			return null;
		}        

		JSch jSch = new JSch();    
		Session session=null;
		Channel channel=null;
		ChannelSftp sftp=null;
        try {
			jSch.addIdentity(
			    USER, 		        // String userName
			    prvkey,             // byte[] privateKey 
			    null,               // byte[] publicKey
			    emptyPassPhrase     // byte[] passPhrase
			);
		        
	        UserInfo ui = new MyUserInfo();
	        session = jSch.getSession(USER, HOST, PORT);
	        session.setUserInfo(ui);
	        session.connect();
	        
	        channel = session.openChannel("sftp");
	        sftp = (ChannelSftp) channel;
	        sftp.connect();
	        
		    results = sftp.get(SRC_PATH + filename);
		    
//		    sftp.disconnect();	        
//	        session.disconnect(); 
		    
	        return results;
        } catch (JSchException e) {
        	System.out.println("ERROR GET RESPONSE : " + e);
			return null;
		} catch (SftpException e) {
			System.out.println("ERROR GET RESPONSE : " + e);
			return null;
		} 
    }
	
	/*
	 * generate by format : CMAddHHmmSSss
	 */
	public static String generateFilename(String suffix) {
		return suffix + MyDateUtils.dateToStr(Constant.FORMAT_EQ_FILE, new Date());
	}
}

class MyUserInfo implements UserInfo {

    private String password;
    
    public MyUserInfo() {
    }
    
    public void setPassword(String password) {
        this.password = password;

    }

    public String getPassphrase() {
        // TODO Auto-generated method stub
        return null;
    }

    public String getPassword() {
        // TODO Auto-generated method stub
        return password;
    }

    public boolean promptPassword(String arg0) {
        // TODO Auto-generated method stub
        return true;
    }

    public boolean promptPassphrase(String arg0) {
        // TODO Auto-generated method stub
        return true;
    }

    public boolean promptYesNo(String arg0) {
        // TODO Auto-generated method stub
        return true;
    }

    public void showMessage(String arg0) {
        // TODO Auto-generated method stub
        System.out.println(arg0);
    }
}
